package com.ls.mysql.util;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * @Author Maple.Chen
 * @Description 邮件发送工具类
 * @Date 10:19 2020/5/27
 **/
public class MyEmailUtil {

    // 1号代理的服务地址及其口令
    private static String EMAIL_OF_RANSMITER_1 = "728067113@qq.com";
    private static String KEY_OF_RANSMITER_1 = "flowdoarmhfmbbce";

    /*
    发送纯文本类型的邮件
     */
    public static boolean machine1(String targetEmail, String title, String msgContent) {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auto", "true");
        properties.setProperty("mail.transport.protol", "smtp");
        properties.setProperty("mail.smtp.host", "smtp.qq.com");
        Session session = Session.getInstance(properties);
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(EMAIL_OF_RANSMITER_1));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(targetEmail));
            message.setSubject(title, "utf-8");
            //邮件内容
            message.setContent(msgContent, "text/html;charset=utf-8");
            message.setSentDate(new Date());
            Transport transport = session.getTransport();
            transport.connect(EMAIL_OF_RANSMITER_1, KEY_OF_RANSMITER_1);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (AddressException e) {
            e.printStackTrace();
            return false;
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            return false;
        } finally {
            // 释放资源
        }
        return true;
    }

}
